import { thin } from "../thin3.mjs";
import datarover from "./datarover.mjs";
import { lazyload } from "./lazyload.mjs";
import { datarows, tablehead } from "./table_helper.mjs";

export function lazyloadlist_template({ container, template }) {
	// console.log({ container, template });
	lazyloadlist({ ...template.lazyloadlist, ...{ container } });
}
export function lazyloadlist({
	container,
	listapi,
	listquery,
	listcols,
	listheight,
	listdatapath,
	rowclick,
	rowselect
}) {
	// console.log({ container, listapi, listquery, listcols, listdatapath });

	let lazyloadlist = document.createElement("lazyloadlist");
	container.appendChild(lazyloadlist);
	let table = document.createElement("table");
	lazyloadlist.appendChild(table);

	if (listheight === "auto") {
		lazyloadlist.style.height = `calc(100% - ${lazyloadlist.offsetTop}px)`;
		lazyloadlist.style.width = `calc(100% - ${lazyloadlist.offsetLeft}px)`;
	} else if (listheight) {
		lazyloadlist.style.height = listheight;
	}

	if (rowselect) {
		listcols.unshift({
			col: {
				input: "",
				type: "checkbox",
				class: "rowselect",
				event: {
					change: (e) => {
						selecthandler();
					}
				}
			},
			filter: {
				input: "",
				type: "checkbox",
				class: "selectall",
				event: {
					change: (e) => {
						// console.log(e);
						thin("input.rowselect", container).each((node) => {
							node.checked = e.sender.checked;
						});
						selecthandler();
					}
				}
			},
			title: "",
			class: "fixed"
		});
	}

	function selecthandler() {
		// console.log({selecthandler})
		if (typeof rowselect === "function") {
			let selected = [];
			thin("input.rowselect", container).each((node) => {
				if (node.checked) selected.push(node.closest("tr").thin_data);
			});
			// console.log(selected);
			rowselect(selected);
		}
	}

	tablehead(table, listcols, onfilter);

	loaddata({ filter: {} });
	function onfilter(filter) {
		console.log(filter);
		loaddata({ filter });
	}

	function loaddata({ filter }) {
		thin("lazyload", table).remove();
		thin("lazyloadtriger", table).remove();
		lazyload({
			container: table,
			api: listapi,
			query: { ...listquery, ...filter },
			success: render
		});
	}
	function render({ container, data, params }) {
		table.thin_data = data;
		console.log({ table });
		let rows = datarover(data, listdatapath);
		datarows({ container, rows, cols: listcols, rowclick });
	}
}
